//
//  LoginViewController3.m
//  UIScrollView的快速使用
//
//  Created by hongfei tam on 2019/3/1.
//  Copyright © 2019 YQ05. All rights reserved.
//

#import "LoginViewController3.h"
#import "MKConstant.h"
#import "DataSource.h"

#import "network.h"
#import "registerVC.h"
#import "resetPwdVC.h"

#import "DB/DataPersist.h"

@interface LoginViewController3 ()<UITextFieldDelegate>{
    UIView *content;
    UITextField *activeField;
    UITextField *usernameTF;
    UITextField *userpassTF;
    
    UIActivityIndicatorView *loadActivity;  //加载动画
    UIView *activityBg;
    
    registerVC *regvc;
    resetPwdVC *resetvc;
}


@end

@implementation LoginViewController3

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = BGGRAYCOLOR;//[UIColor lightGrayColor];
    
    content = [[UIView alloc]initWithFrame:CGRectMake( 60/2, (UISCREEN_HEIGHT - 360)/2, UISCREEN_WIDTH - 60, 360)];
    content.backgroundColor = [UIColor whiteColor];
    content.layer.shadowColor = [UIColor grayColor].CGColor;
    content.layer.shadowOffset = CGSizeMake(3, 3);
    content.layer.shadowOpacity = 0.8;
    
    ////  圆角效果
    content.layer.cornerRadius = 2;
    content.layer.borderColor = [UIColor grayColor].CGColor;
    content.layer.borderWidth = 1;
    
    //  视图添加方法：addSubview 参数：view
    [self.view addSubview:content];
    
    activeField = [[UITextField alloc]init];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(keyboardHide:)];
    tap.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:tap];
    
    //接收提交信息
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(loginstatusAction:) name:@"loginstatus" object:nil];
    
    
    [self titleLabel]; //标题
    [self nameTF];
    [self pwdTF];

    [self forgetBtn];
    [self submitBtn];
    [self registerLabel];
    [self registerBtn];
    // Do any additional setup after loading the view.
}

-(void)titleLabel{
    //  3 字体
    UILabel *label3 = [[UILabel alloc]initWithFrame:CGRectMake(0, 10, content.bounds.size.width, 50)];
    //label3.backgroundColor = MENUBROWN;// 背景色
    label3.text = @"登入";// 内容
    label3.textColor = MENUBROWN; //内容颜色
    //  使用字体名称
    //label3.font = [UIFont fontWithName:@"Aril-BoldMT" size:15.0];
    label3.font = [UIFont systemFontOfSize:26.0];
    //  对其方式: text内容 相对 uilabel command＋鼠标左键
    label3.textAlignment = NSTextAlignmentCenter;
    
    [content addSubview:label3];
}

// 属性
-(void)nameTF{
    usernameTF = [[UITextField alloc]initWithFrame:CGRectMake(40/2, 60, content.bounds.size.width - 40, 40)];
    usernameTF.borderStyle = UITextBorderStyleLine;// 边框
    //text1.textColor = [UIColor redColor];// text 字体颜色 内容字体大小
    
    usernameTF.font = [UIFont systemFontOfSize:17.0];
    usernameTF.placeholder = @"請輸入電郵";// 提示
    
 
    //    UITextField *textfield = [[UITextField alloc]initWithFrame:CGRectMake(10, 50, 300, 30)];
    //    textfield.borderStyle = UITextBorderStyleLine;// 边框
    //    textfield.textColor = [UIColor redColor];// text 字体颜色 内容字体大小
    //    textfield.font = [UIFont systemFontOfSize:17.0];
    //    textfield.placeholder = @"please enter text";// 提示
    
    usernameTF.keyboardType = UIKeyboardTypeEmailAddress;
    //    UIKeyboardTypeDefault,                // Default type for the current input method.
    //    UIKeyboardTypeASCIICapable,           // Displays a keyboard which can enter ASCII characters
    //    UIKeyboardTypeNumbersAndPunctuation,  // Numbers and assorted punctuation.
    //    UIKeyboardTypeURL,                    // A type optimized for URL entry (shows . / .com prominently).
    //    UIKeyboardTypeNumberPad,              // A number pad with locale-appropriate digits (0-9, ۰-۹, ०-९, etc.). Suitable for PIN entry.
    //    UIKeyboardTypePhonePad,               // A phone pad (1-9, *, 0, #, with letters under the numbers).
    //    UIKeyboardTypeNamePhonePad,           // A type optimized for entering a person's name or phone number.
    //    UIKeyboardTypeEmailAddress,           // A type optimized for multiple email address entry (shows space @ . prominently).
    //    UIKeyboardTypeDecimalPad NS_ENUM_AVAILABLE_IOS(4_1),   // A number pad with a decimal point.
    //    UIKeyboardTypeTwitter NS_ENUM_AVAILABLE_IOS(5_0),      // A type optimized for twitter text entry (easy access to @ #)
    //    UIKeyboardTypeWebSearch NS_ENUM_AVAILABLE_IOS(7_0),    // A default keyboard type with URL-oriented addition (shows space . prominently).
    //    UIKeyboardTypeASCIICapableNumberPad NS_ENUM_AVAILABLE_IOS(10_0),
    usernameTF.returnKeyType = UIReturnKeyDone;
    //设置UITextField的边框样式
    usernameTF.borderStyle = UITextBorderStyleRoundedRect;//圆角
    //    UITextBorderStyleNone, // 无边框
    //    UITextBorderStyleLine, // 有黑色边框
    //    UITextBorderStyleBezel, // 有灰色边框和阴影
    //    UITextBorderStyleRoundedRect // 圆角
    
    usernameTF.clearButtonMode = UITextFieldViewModeWhileEditing; //输入框右侧删除按钮  在UITextField文本框中开始编辑的时候显示清除设置，点击清除按钮删除内容
    usernameTF.delegate = self;// 谁来响应
    [content addSubview:usernameTF];
}

// textfiled
-(void)pwdTF{
    userpassTF = [[UITextField alloc]initWithFrame:CGRectMake(40/2, 110, content.bounds.size.width - 40, 40)];
    userpassTF.borderStyle = UITextBorderStyleLine;// 边框
    //text2.textColor = [UIColor redColor];// text 字体颜色 内容字体大小
    userpassTF.secureTextEntry = YES; //密码
    userpassTF.font = [UIFont systemFontOfSize:17.0];
    userpassTF.placeholder = @"請輸入密碼";// 提示
    
    userpassTF.keyboardType = UIKeyboardTypeEmailAddress;
    
    //    UITextField *textfield = [[UITextField alloc]initWithFrame:CGRectMake(10, 50, 300, 30)];
    //    textfield.borderStyle = UITextBorderStyleLine;// 边框
    //    textfield.textColor = [UIColor redColor];// text 字体颜色 内容字体大小
    //    textfield.font = [UIFont systemFontOfSize:17.0];
    //    textfield.placeholder = @"please enter text";// 提示
    
    userpassTF.keyboardType = UIKeyboardTypeDefault;
    //    UIKeyboardTypeDefault,                // Default type for the current input method.
    //    UIKeyboardTypeASCIICapable,           // Displays a keyboard which can enter ASCII characters
    //    UIKeyboardTypeNumbersAndPunctuation,  // Numbers and assorted punctuation.
    //    UIKeyboardTypeURL,                    // A type optimized for URL entry (shows . / .com prominently).
    //    UIKeyboardTypeNumberPad,              // A number pad with locale-appropriate digits (0-9, ۰-۹, ०-९, etc.). Suitable for PIN entry.
    //    UIKeyboardTypePhonePad,               // A phone pad (1-9, *, 0, #, with letters under the numbers).
    //    UIKeyboardTypeNamePhonePad,           // A type optimized for entering a person's name or phone number.
    //    UIKeyboardTypeEmailAddress,           // A type optimized for multiple email address entry (shows space @ . prominently).
    //    UIKeyboardTypeDecimalPad NS_ENUM_AVAILABLE_IOS(4_1),   // A number pad with a decimal point.
    //    UIKeyboardTypeTwitter NS_ENUM_AVAILABLE_IOS(5_0),      // A type optimized for twitter text entry (easy access to @ #)
    //    UIKeyboardTypeWebSearch NS_ENUM_AVAILABLE_IOS(7_0),    // A default keyboard type with URL-oriented addition (shows space . prominently).
    //    UIKeyboardTypeASCIICapableNumberPad NS_ENUM_AVAILABLE_IOS(10_0),
    userpassTF.returnKeyType = UIReturnKeyDone;
    //设置UITextField的边框样式
    userpassTF.borderStyle = UITextBorderStyleRoundedRect;//圆角
    //    UITextBorderStyleNone, // 无边框
    //    UITextBorderStyleLine, // 有黑色边框
    //    UITextBorderStyleBezel, // 有灰色边框和阴影
    //    UITextBorderStyleRoundedRect // 圆角
    
    userpassTF.clearButtonMode = UITextFieldViewModeWhileEditing; //输入框右侧删除按钮  在UITextField文本框中开始编辑的时候显示清除设置，点击清除按钮删除内容
    userpassTF.delegate = self;// 谁来响应
    [content addSubview:userpassTF];
}

-(void)forgetBtn{
    //   1 UI实例化 2 UI属性 3view 添加
    //initWithFrame:UI实例化 Frame
    //  UI+XX
    UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(20, 170, 150, 30)];
    //  作用：为Button 添加一个内容 1:title 2状态
    [button setTitle:@"忘記密碼？" forState:UIControlStateNormal];
    //  作用：为Button 内容设置颜色 1:title颜色 2状态
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    
    //但是问题又出来，此时文字会紧贴到做边框，我们可以设置
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    
    
    //使文字距离做边框保持10个像素的距离。
    //button.contentEdgeInsets = UIEdgeInsetsMake(0,10, 0, 0);
    
    
    
    //  作用：是为button添加响应方法 1 self 2@selector(方法名) 3UIControlEventTouchUpInside:点击之后
    //  :
    [button addTarget:self action:@selector(resetBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [content addSubview:button];
}
//  谁调用 bt 谁传递过来的
-(void)resetBtnAction:(UIButton*)bt{
    NSLog(@"忘記密碼？！");
    
    UIStoryboard * sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];  //获取SB
    if (resetvc == nil) {
        resetvc = [sb instantiateViewControllerWithIdentifier:@"resetPwdVC"];  //获取SB 上VC id
    }
    [self.navigationController pushViewController:resetvc animated:YES];   //同一个navigationController。推出子视图

}


-(void)submitBtn{
    //   1 UI实例化 2 UI属性 3view 添加
    //initWithFrame:UI实例化 Frame
    //  UI+XX
    UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake((content.bounds.size.width - 140)/2, 220, 140, 40)];
    
    //  作用：为Button 添加一个内容 1:title 2状态
    [button setTitle:@"立刻登入" forState:UIControlStateNormal];
    //  作用：为Button 内容设置颜色 1:title颜色 2状态
    [button setTitleColor:MENUBROWN forState:UIControlStateNormal];
    
    [button setBackgroundImage:[UIImage imageNamed:@"botton_140x40.jpg"] forState:UIControlStateNormal];
    
    //但是问题又出来，此时文字会紧贴到做边框，我们可以设置
    //button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    
    //使文字距离做边框保持10个像素的距离。
    //button.contentEdgeInsets = UIEdgeInsetsMake(0,10, 0, 0);
    
    
    
    //  作用：是为button添加响应方法 1 self 2@selector(方法名) 3UIControlEventTouchUpInside:点击之后
    //  :
    [button addTarget:self action:@selector(submitBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [content addSubview:button];
}
//  谁调用 bt 谁传递过来的
-(void)submitBtnAction{
    NSLog(@"submit？！");
    [self submitAction];

}

-(void)registerLabel{
    //  3 字体
    //UILabel *label3 = [[UILabel alloc]initWithFrame:CGRectMake(70, 290, 120, 30)];
    UILabel *label3 = [[UILabel alloc]initWithFrame:CGRectMake((UISCREEN_WIDTH - 120 -120 - 30)/2, 290, 120, 30)];
    //label3.backgroundColor = MENUBROWN;// 背景色
    label3.text = @"沒有賬戶？";// 内容
    label3.textColor = [UIColor lightGrayColor]; //内容颜色
    //  使用字体名称
    //label3.font = [UIFont fontWithName:@"Aril-BoldMT" size:15.0];
    label3.font = [UIFont systemFontOfSize:20.0];
    //  对其方式: text内容 相对 uilabel command＋鼠标左键
    //label3.textAlignment = NSTextAlignmentCenter;
    
    [content addSubview:label3];
}

-(void)registerBtn{
    //   1 UI实例化 2 UI属性 3view 添加
    //initWithFrame:UI实例化 Frame
    //  UI+XX
    //UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(160, 290,  110, 30)];
    UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake((UISCREEN_WIDTH - 80 )/2, 290,  110, 30)];
    //  作用：为Button 添加一个内容 1:title 2状态
    [button setTitle:@"註冊新賬戶" forState:UIControlStateNormal];
    //  作用：为Button 内容设置颜色 1:title颜色 2状态
    [button setTitleColor:MENUBROWN forState:UIControlStateNormal];
    
    button.titleLabel.font = [UIFont systemFontOfSize: 20.0];  //字體大小
    
    //[button setBackgroundImage:[UIImage imageNamed:@"botton_140x40.jpg"] forState:UIControlStateNormal];
    
    //但是问题又出来，此时文字会紧贴到做边框，我们可以设置
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    
    //使文字距离做边框保持10个像素的距离。
    //button.contentEdgeInsets = UIEdgeInsetsMake(0,10, 0, 0);
    
    
    
    //  作用：是为button添加响应方法 1 self 2@selector(方法名) 3UIControlEventTouchUpInside:点击之后
    //  :
    [button addTarget:self action:@selector(registerBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [content addSubview:button];
}
//  谁调用 bt 谁传递过来的
-(void)registerBtnAction:(UIButton*)bt{
    NSLog(@"registerBtn？！");
    //NSLog(@"click 查看登陆flag %id",[[DataSource getInstance]getLoginFlag]);
    UIStoryboard * sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];  //获取SB
    if (regvc == nil) {
        regvc = [sb instantiateViewControllerWithIdentifier:@"registerVC"];  //获取SB 上VC id
    }
[self.navigationController pushViewController:regvc animated:YES];   //同一个navigationController。推出子视图
    
}


#pragma mark - 提交信息
////接收提交信息
//-(void)notifAction:(NSNotification*)notif{
//    NSDictionary *dic = notif.userInfo;
//    //    NSLog(@"s接受到的 字典。%@",dic);
//    //    NSString *string = [dic valueForKey:@"name"]; //pagetitle
//    //    NSLog(@"%@",string);
//    [self submitAction:dic];
//}
-(void)showAlert:(NSString *)title message:(NSString *)message{  //警告弹出框
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDestructive handler:nil];
    [alertController addAction:okAction];
    [self presentViewController:alertController animated:true completion:nil];
}

-(void)submitAction{
    
    NSString *username = [usernameTF.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    NSString *userpass = [userpassTF.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    
    
    // 正则
    if ([username containsString:@"#"] || [username containsString:@"$" ] || [username containsString:@"%"]) {
        [self showAlert:@"警告！" message: @"包含非法字符！"];
    }else if (userpass.length<6){
        //NSLog(@"userpass %@",userpass);
        [self showAlert:@"警告！" message: @"密碼长度不够！"];
    }else{
        [self loadingView];
        
        
        NSMutableDictionary *senddic = [[NSMutableDictionary alloc]init];
        [senddic setValue:username forKey:@"username"];
        [senddic setValue:userpass forKey:@"userpass"];
        
        NSString *fcmToken = [DataPersist readValuePre:@"fcmToken"];
        [senddic setValue:fcmToken forKey:@"fcmToken"];
        //[senddic setValue:useremail forKey:@"useremail"];
        
        
        //[self showAlert:@"发送消息" message: @"发送消息成功"];
        network *sendNetWork = [[network alloc]init];
        [sendNetWork POSTrequest:YOUNGURL type:@"login" senddic:senddic savekey:@"login"];  //发送数据
       
    }
    
}

-(void)loadingView{  //等待网络结果动画
    
    CGRect frame = CGRectMake(0, 0, 100, 100);
    //UIView *activityBg = [[UIView alloc]initWithFrame:frame];
    activityBg = [[UIView alloc]initWithFrame:frame];
    activityBg.center = self.view.center;
    activityBg.backgroundColor = [UIColor grayColor];
    activityBg.alpha = 0.7;
    activityBg.layer.cornerRadius = 5.0;
    [self.view addSubview:activityBg];
    
    //UIActivityIndicatorView *loadActivity = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    
    loadActivity = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    loadActivity.frame = CGRectMake(30, 30, 40, 40);
    [loadActivity sizeToFit];
    loadActivity.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
    [activityBg addSubview:loadActivity];
    [loadActivity startAnimating];
    //     //网络请求 延迟时间
    //    dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, 5000*NSEC_PER_MSEC);
    //    // 延迟方法
    //    // 1 delayTime 2 thread 3 代码
    //    dispatch_after(delayTime, dispatch_get_main_queue(), ^{
    //        [loadActivity stopAnimating];
    //        [activityBg removeFromSuperview];
    //        [self dismissViewControllerAnimated:true completion:nil];
    ////        [self setindexdata]; //设置首页数据
    ////        [self setMenuData];
    ////        [self settableView];
    //    });
    
}
-(void)stoploading{ //d停止动画
    [loadActivity stopAnimating];
    [activityBg removeFromSuperview];
}

-(void)loginstatusAction:(NSNotification*)notif{
    
        dispatch_async(dispatch_get_main_queue(), ^{  //get 主线程
            [self stoploading];
            NSNumber *num = notif.object;
            int num2 = num.intValue;
//             NSLog(@"num2 %d",num2);
            
            if (num2 == 1) {
              [self.navigationController popToRootViewControllerAnimated:YES]; //IOS 返回根视图
            }else{
                NSDictionary *dic = notif.userInfo;
                //    NSString *statusnum1 = [dic valueForKey:@"loginstatus"];
                //    int statusnum = statusnum1.intValue;
                
                NSString *loginstatus = [dic valueForKey:@"loginstatus"];
             
                NSLog(@"currentThread %@ ",[NSThread currentThread]);
                    
                [self showAlert:@"消息" message: loginstatus];
            }
            //NSLog(@"currentThread %@ ",[NSThread currentThread]);
        });
}


-(void)dealloc{
    
    //销毁的时候别忘移除监听
    //[self.webView.scrollView removeObserver:self forKeyPath:@"contentSize"];
    //接受信息 广播
    //[[NSNotificationCenter defaultCenter]removeObserver:self name:@"Promotionsend" object:nil];
    
    //接受信息 广播 发送成功信息
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"loginstatus" object:nil];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

// 输入完成之后被调用
//-(void)textFieldDidEndEditing:(UITextField *)textField{
//    NSLog(@"text=%@",textField.text);
//}
// 点击done之后被调用
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    //NSLog(@"tag=%ld",(long)textField.tag);
    [textField resignFirstResponder];//取消当前键盘输入响应
    return true;
}

/**
 *   键盘遮挡
 */
-(void)keyboardHide:(UITapGestureRecognizer*)tap{
    [activeField resignFirstResponder];
}

-(void)viewWillAppear:(BOOL)animated{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHidden:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)keyboardWasShown:(NSNotification*)aNotification
{
    CGFloat kbHeight = [[aNotification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;//獲取鍵盤高度
    CGFloat offset0 = (activeField.frame.origin.y+activeField.frame.size.height) - (self.view.frame.size.height - kbHeight);//增加的高度
    double duration = [[aNotification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    if(offset0 > 0) {
        [UIView animateWithDuration:duration animations:^{
            self.view.frame = CGRectMake(0.0f, -offset0-10, self.view.frame.size.width, self.view.frame.size.height);
        }];
    }
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    activeField = textField;
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    activeField = nil;
}

- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    double duration = [[aNotification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    [UIView animateWithDuration:duration animations:^{
        self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    }];
}

@end
